package com.tutu.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tutu.reggie.common.CustomException;
import com.tutu.reggie.common.R;
import com.tutu.reggie.dto.SetmealDto;
import com.tutu.reggie.entity.Category;
import com.tutu.reggie.entity.Dish;
import com.tutu.reggie.entity.Setmeal;
import com.tutu.reggie.service.CategoryService;
import com.tutu.reggie.service.DishService;
import com.tutu.reggie.service.SetmealDishService;
import com.tutu.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 新增套餐
     *
     * @param setmealDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> save(@RequestBody SetmealDto setmealDto) {
        log.info("新增的套餐信息:{}", setmealDto);
        setmealService.saveWithDish(setmealDto);
        return R.success("新套餐添加成功！！！");
    }

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        //分页构造器对象
        Page<Setmeal> pageInfo = new Page<>(page, pageSize);
        Page<SetmealDto> dtoPage = new Page<>();
        //条件构造器
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();

        //添加查询条件  根据name进行模糊查询
        queryWrapper.like(name != null, Setmeal::getName, name);

        //添加排序条件 根据更新时间降序排列
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);

        setmealService.page(pageInfo, queryWrapper);
        //对象拷贝  将pageInfo对象的值拷贝到dtoPage对象上   忽略records
        BeanUtils.copyProperties(pageInfo, dtoPage, "records");
        List<Setmeal> records = pageInfo.getRecords();

        List<SetmealDto> list = records.stream().map((item) -> {
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(item, setmealDto);
            Long categoryId = item.getCategoryId();
            //根据categoryId查询对应的categoryName
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                setmealDto.setCategoryName(categoryName);
            }
            return setmealDto;
        }).collect(Collectors.toList());
        //将获取好的list赋值给dtoPage
        dtoPage.setRecords(list);
        return R.success(dtoPage);
    }

    /**
     * 删除套餐
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> delete(@RequestParam List<Long> ids) {
        log.info("删除的套餐信息ids:{}", ids);
        setmealService.removeWithDish(ids);
        return R.success("删除成功!");
    }


    /**
     * 修改套餐时  根据id查询套餐信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<SetmealDto> getSetmealById(@PathVariable Long id) {
        log.info("修改的菜品id{}", id);
        SetmealDto setmealDto = setmealService.getByIdWithDish(id);
        return R.success(setmealDto);
    }


    /**
     * 修改套餐
     *
     * @param setmealDto
     * @return
     */
    @PutMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> update(@RequestBody SetmealDto setmealDto) {
        log.info("修改的菜品信息{}", setmealDto);
        setmealService.updateWithDish(setmealDto);
        return R.success("套餐修改成功");
    }


    /**
     * 套餐的批量起售 停售
     *
     * @param status
     * @param ids
     */
    @PostMapping("status/{status}")
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> updateSetmealStatus(@PathVariable Integer status, Long[] ids) {
        log.info("修改的菜品信息{}", ids);
        List<Long> list = Arrays.asList(ids);
        //当套餐停售时  直接进行停售
        if (status == 0) {
            LambdaUpdateWrapper<Setmeal> updateWrapper = new LambdaUpdateWrapper<>();
            //添加查询条件
            updateWrapper.set(Setmeal::getStatus, status);
            updateWrapper.in(Setmeal::getId, ids);
            setmealService.update(updateWrapper);
            return R.success("套餐停售成功");
        }
        //当套餐启售时  检查套餐里的菜品是否被删除或以停售
        for (Long id : ids) {
            //根据setmeal_id查找dish_id
            List<Long> dishIDList = setmealService.findDishID(id);
            //遍历dishID 检查该菜品有无被删除或停售
            for (Long dishId : dishIDList) {
                Dish dish = dishService.getById(dishId);
                if (dish.getStatus() == 0) {
                    throw new CustomException("套餐中的" + dish.getName() + "已停售,无法起售该套餐");
                }
            }
            LambdaUpdateWrapper<Setmeal> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(Setmeal::getStatus, status);
            updateWrapper.eq(Setmeal::getId, id);
            setmealService.update(updateWrapper);
        }
        return R.success("套餐起售成功");
    }

    /**
     * 根据套餐id查询出套餐下的套餐种类
     *
     * @param categoryId
     * @param status
     * @return
     */
    @GetMapping("list")
    @Cacheable(value = "setmealCache",key = "#categoryId+'_'+#status")
    public R<List<Setmeal>> getSetmealList(@RequestParam Long categoryId, @RequestParam Integer status) {
        log.info("查询的套餐id:{}", categoryId);
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(categoryId!=null,Setmeal::getCategoryId, categoryId);
        queryWrapper.eq(status!=0,Setmeal::getStatus,status);
        List<Setmeal> list = setmealService.list(queryWrapper);
        return R.success(list);
    }

}
